package com.xiaomei.manager.weixin.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

import com.xiaomei.manager.weixin.entity.DownloadBillDto;

public class HttpXmlUtil {
	/**
	 * post请求并得到返回结果
	 * @param requestUrl
	 * @param requestMethod
	 * @param output
	 * @return
	 */
	public static String httpsRequest(String requestUrl, String requestMethod, String output) {
		try{
			URL url = new URL(requestUrl);
			HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setUseCaches(false);
			connection.setRequestMethod(requestMethod);
			if (null != output) {
				OutputStream outputStream = connection.getOutputStream();
				outputStream.write(output.getBytes("UTF-8"));
				outputStream.close();
			}
			// 从输入流读取返回内容
			InputStream inputStream = connection.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
			String str = null;
			StringBuffer buffer = new StringBuffer();
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			inputStream.close();
			inputStream = null;
			connection.disconnect();
			return buffer.toString();  //将返回的响应内容转化成字符串
		}catch(Exception ex){
			ex.printStackTrace();
		}

		return "";
	}
	
	/**
	 * 构造xml参数
	 * @param xml
	 * @return
	 */
	public static String xmlInfo(DownloadBillDto downbilldto){
	
		if(downbilldto!=null){
			StringBuffer bf = new StringBuffer();
			bf.append("<xml>");

			bf.append("<appid><![CDATA[");
			bf.append(downbilldto.getAppid());
			bf.append("]]></appid>");

			bf.append("<mch_id><![CDATA[");
			bf.append(downbilldto.getMch_id());
			bf.append("]]></mch_id>");

			bf.append("<nonce_str><![CDATA[");
			bf.append(downbilldto.getNonce_str());
			bf.append("]]></nonce_str>");

			bf.append("<sign><![CDATA[");
			bf.append(downbilldto.getSign());
			bf.append("]]></sign>");

			bf.append("<bill_date><![CDATA[");
			bf.append(downbilldto.getBill_date());
			bf.append("]]></bill_date>");

			bf.append("<bill_type><![CDATA[");
			bf.append(downbilldto.getBill_type());
			bf.append("]]></bill_type>");

//			bf.append("<device_info><![CDATA[");
//			bf.append(downbilldto.getDevice_info());
//			bf.append("]]></device_info>");
		
			bf.append("</xml>");
			return bf.toString();
		}
		return "";
	}
	
}
